/**  
* Copyright © 2015 ChangSha 80 Network Technology Co.,Ltd All Rights Reserved 
*/
package com.yiren.dbaa.util;

import android.content.Context;
import android.content.res.AssetManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 附件复制工具类
 */
public class AssetCopyUtil {
	
	  /** The Constant ASSET_LIST_FILENAME. */
  	private static final String ASSET_LIST_FILENAME = "assets.lst";

	  /** The m context. */
  	private final Context mContext;
	  
  	/** The m asset manager. */
  	private final AssetManager mAssetManager;
	  
	  /**
	 * Instantiates a new asset copy util.
	 *
	 * @param context
	 *             the context
	 */
  	public AssetCopyUtil(Context context ) {
	  mContext = context;
	  mAssetManager = context.getAssets();		
	  }
	    
	  /**
	   * 将工程资源文件复制到本地SD卡
	   * @param rootPath  根目录
	   * @param subPath    子目录
	   * @param gcPath    工程目录
	   * @return
	   * @throws IOException
	   */
	  public boolean copyToPath(String rootPath,String subPath,String gcPath) throws IOException {
	      File mAppDirectory = new File(rootPath);
	      if (null == mAppDirectory) {
	    	  return false;
	      }
		  //如果不存在，则copy
		  if(!new File(mAppDirectory,subPath).exists()) {
			  copy(mAppDirectory,subPath,gcPath);
		  }
	      return true;
	}
	  
	  
	  /**
	 * 获取需要拷贝的文件列表（记录在assets/assets.lst文件中）
	 *
	 * @return 文件列表
	 * @throws IOException
	 *              Signals that an I/O exception has occurred.
	 */
	  protected List<String> getAssetsList() throws IOException {
	      List<String> files = new ArrayList<String>();
	      InputStream listFile = mAssetManager.open(new File(ASSET_LIST_FILENAME).getPath());
	      BufferedReader br = new BufferedReader(new InputStreamReader(listFile));
	      String path;
	      while (null != (path = br.readLine())) {
	    	  files.add(path);
	      }
	      return files;
	  }
	    
	 
	  protected File copy(File mAppDirectory,String subPath,String gcPath) throws IOException {
		  File destinationFile = new File(mAppDirectory, subPath);
		  destinationFile.getParentFile().mkdirs();
		  InputStream source = mAssetManager.open(new File(gcPath).getPath());
		  OutputStream destination = new FileOutputStream(destinationFile);
		  byte[] buffer = new byte[1024];
		  int nread;

		  while ((nread = source.read(buffer)) != -1) {
			  if (nread == 0) {
				  nread = source.read();
				  if (nread < 0)
					  break;
				  destination.write(nread);
				  continue;
			  }
			  destination.write(buffer, 0, nread);
		  }
	      destination.close();
	        
	      return destinationFile;
	    }
}
